package com.jerkin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jerkin.annotations.ProxyTest;
import com.jerkin.mapper.StudentMapper;
import com.jerkin.model.StudentDo;
import com.jerkin.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;

/**
 * @version V1.0
 * @ClassName: StudentServiceImpl
 * @Description:
 * @author: huhongzhi
 * @date: 2019/11/28 14:38
 */
@Slf4j
@Service("studentService")
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    @ProxyTest
    @Transactional
    @Override
    public void add(StudentDo studentDo, Boolean flag) {
        try {
//            studentMapper.add(studentDo);
            try {
                addStudent(studentDo);
            } catch (Throwable e) {
                log.info("执行的异常:"+e.getMessage());
            }
            if (flag) {
                TransactionSynchronizationManager.registerSynchronization(
                        new TransactionSynchronizationAdapter() {

                            @Override
                            public void beforeCommit(boolean readOnly) {
                                log.info("事务提交之前执行");
                            }

                            @Override
                            public void beforeCompletion() {
                                log.info("事务完成之前执行");
                            }

                            @Override
                            public void afterCommit() {
                                log.info("事务提交后执行");
                            }

                            @Override
                            public void afterCompletion(int status) {
                                log.info("事务提交或回滚完成后执行");
                            }
                        }
                );
            }

        } catch (Exception e) {
            log.info("抛出异常进行数据回滚");
            throw new RuntimeException(e);
        } finally {
            log.info("执行finally方法");
        }
    }

//    @Transactional
    public void addStudent(StudentDo studentDo) throws Throwable {
        studentMapper.add(studentDo);
        throw new Throwable("抛出测试回滚异常");
    }

    @Override
    public PageInfo<StudentDo> queryByCondition(Integer id) {
        PageInfo<StudentDo> page = PageHelper.startPage(1, 10)
                .doSelectPageInfo(() -> {
                    studentMapper.queryByConditon(id);
                });
        return page;
    }

}
